<template>
  <div>
    <!-- <div class="form-header">
      <el-button @click="handleCacel">取消</el-button>
      <el-button :disabled="disabled" type="primary" @click="handleQuery">保存</el-button>
    </div> -->
    <div class="page">
      <DynamicForm
        ref="queryRef"
        v-model="queryParams"
        :disabled="disabled"
        :config="formConfigDetail"
        :items="formItemsDetail"
        :dict-data="{ sys_user_sex }">
        <template #caseId>
          <!-- 立案号 -->
          <el-select v-model="queryParams.caseId" clearable @change="handleCaseNoChange">
            <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </template>
        <template #dateRange="{ formData, item }">
          <!--  -->
          <el-date-picker
            v-model="queryParams.dateRange"
            type="datetimerange"
            end-placeholder="结束日期"
            start-placeholder="开始日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            range-separator="-"
            :style="item.style" />
        </template>
        <template #recorderId>
          <el-select
            v-model="queryParams.recorderId"
            clearable
            filterable
            placeholder="请选择记录人"
            @change="handleRecorderName">
            <el-option
              v-for="(item, index) in check_person"
              :key="item.value"
              :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </template>
        <template #recordAddress>
          <el-input v-model="queryParams.recordAddress" placeholder="请输入"></el-input>
        </template>
        <template #streetOfAddress>
          <el-row :gutter="20">
            <el-col :span="7">
              <el-input :value="settings.cityName" disabled placeholder="城市"></el-input>
            </el-col>
            <el-col :span="7">
              <el-input :value="settings.areaName" disabled placeholder="区县"></el-input>
            </el-col>
            <el-col :span="10">
              <el-select v-model="queryParams.streetOfAddress" clearable filterable placeholder="请选择街道">
                <el-option
                  v-for="(item, index) in street_of_area"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </template>
        <template #address>
          <el-input v-model="queryParams.address" placeholder="详细地址"></el-input>
        </template>
      </DynamicForm>
      <div class="form-title-wrapper">
        <div class="form-title-text">询问内容</div>
      </div>
      <el-form
        ref="ruleFormRef"
        :model="queryParams"
        :rules="rules"
        :disabled="disabled"
        label-width="80px"
        class="demo-ruleForm"
        status-icon>
        <el-row v-for="(item, index) in queryParams.tsurveyInquiryRecordList" :gutter="20" :key="item.id">
          <el-col :span="11">
            <el-form-item label="问" :rules="rules.ask" :prop="`tsurveyInquiryRecordList.${index}.ask`">
              <SmartTextInput
                v-model="queryParams.tsurveyInquiryRecordList[index].ask"
                type="textarea"
                :rows="1"
                placeholder="请输入"
                :min-length="2"
                :max-suggestions="5"
                contentType="100" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="答" :rules="rules.answer" :prop="`tsurveyInquiryRecordList.${index}.answer`">
              <SmartTextInput
                v-model="queryParams.tsurveyInquiryRecordList[index].answer"
                type="textarea"
                :rows="1"
                placeholder="请输入"
                :min-length="2"
                :max-suggestions="5"
                contentType="100" />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="line-action">
            <el-icon @click="handleAdd"><Plus /></el-icon>
            <el-icon style="color: var(--el-color-danger)" @click="handleRemove(index)"><Minus /></el-icon>
          </el-col>
        </el-row>
      </el-form>
      <div class="form-footer">
        <el-button @click="handleCacel">取消</el-button>
        <el-button :loading="preViewLoading" @click="handlePreview">预览</el-button>
        <el-button :disabled="disabled" type="primary" @click="handleQuery">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import DynamicForm from '@/components/DynamicForm/index.vue'
import SmartTextInput from '@/components/SmartTextInput/index.vue'
import { pageConfig } from './config'
import { ElMessage } from 'element-plus'
import settings from '@/settings.js'
import {
  getCaseList,
  getContent,
  saveInquiry,
  updateInquiry,
  getInquiryDetail,
  previewInquiryPdf,
} from '@/api/inquiry/index'
import useUserStore from '@/store/modules/user'
import { getUserEnforcementNo } from '@/api/system/user.js'

const router = useRouter()
const route = useRoute()
const query = route.query
if (query.formId) {
  nextTick(() => {
    getDetail(query.formId as string)
  })
}
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const { sys_user_sex, street_of_area } = proxy.useDict('sys_user_sex', 'street_of_area')

const disabled = route.query.type === 'view'

const { formConfigDetail, formItemsDetail } = pageConfig()
const queryRef = ref<any>(null)
const ruleFormRef = ref<any>(null)
const queryParams = ref<any>({
  caseId: '', // 立案号
  dateRange: [] as string[], // 时间
  recordWorkUnit: '北京市大兴区生态环保局',
  streetOfAddress: '',
  address: '',
  recordAddress: userStore.address,
  tsurveyInquiryRecordList: [{ id: 1, ask: undefined, answer: undefined }],
})
const rules = {
  ask: [{ required: true, message: '请输入', trigger: ['blur', 'change'] }],
  answer: [{ required: true, message: '请输入', trigger: ['blur', 'change'] }],
}

// 立案号相关 start ==================================================================
const numberList = ref<any>([])
const getNumberList = () => {
  getCaseList().then((res: any) => {
    numberList.value = res.data.map((item: any) => ({
      label: item.caseNo,
      value: item.id,
    }))
  })
}
// 选中立案号
const handleCaseNoChange = async (value: any) => {
  if (!value) {
    return
  }
  const res: any = await getContent({ caseId: value })
  const { data } = res
  queryParams.value.caseNo = numberList.value.find((item: any) => item.value === value)?.label
  queryParams.value.dateOfBirth = data.dateOfBirth
  queryParams.value.gender = data.gender
  queryParams.value.idNumber = data.idNumber
  queryParams.value.inspectorName1 = data.inspectorName1
  queryParams.value.inspectorCertNo1 = data.inspectorCertNo1
  queryParams.value.inspectorName2 = data.inspectorName2
  queryParams.value.inspectorCertNo2 = data.inspectorCertNo2
  queryParams.value.onsiteName = data.onsiteName
  queryParams.value.onsitePhone = data.onsitePhone
  queryParams.value.onsitePosition = data.onsitePosition
  queryParams.value.postalCode = data.postalCode
  queryParams.value.address = data.address
  queryParams.value.streetOfAddress = data.streetOfAddress
  queryParams.value.workUnit = data.workUnit
}
// 立案号相关 end ==================================================================

// 选中记录人
const check_person = ref<any>([])
const getUserList = async () => {
  const res = await getUserEnforcementNo({})
  if (res.data.length > 0) {
    check_person.value = res.data.map((item: any) => {
      return { value: item.userId, label: item.name, enforcementNo: item.enforcementNo }
    })
  }
}
getUserList()
const handleRecorderName = val => {
  check_person.value.forEach(item => {
    if (item.value === val) {
      queryParams.value.recordEnforcementNo = item.enforcementNo
      queryParams.value.recorderName = item.label
    }
  })
}

// 获取详情
const getDetail = async (id: string) => {
  const res: any = await getInquiryDetail(id)
  const { data } = res
  queryParams.value = {
    ...data,
    dateRange: data.recordStartTime && data.recordEndTime ? [data.recordStartTime, data.recordEndTime] : [],
    tsurveyInquiryRecordList:
      data.tsurveyInquiryRecordList && data.tsurveyInquiryRecordList.length > 0
        ? data.tsurveyInquiryRecordList
        : [{ id: 1, ask: undefined, answer: undefined }],
  }
}

// 添加询问内容
const handleAdd = () => {
  queryParams.value.tsurveyInquiryRecordList.push({ id: new Date().getTime(), ask: undefined, answer: undefined })
}
// 删除询问内容
const handleRemove = (index: number) => {
  if (queryParams.value.tsurveyInquiryRecordList.length === 1) {
    ElMessage.error('至少保留一个询问内容')
    return
  }
  queryParams.value.tsurveyInquiryRecordList.splice(index, 1)
}
// 预览
const preViewLoading = ref(false)
const handlePreview = () => {
  preViewLoading.value = true
  handleQuery(true)
    .then(async params => {
      const res: any = await previewInquiryPdf(params)
      if (!!res.msg) {
        window.open(res.msg)
      } else {
        ElMessage.warning('预览文件不存在')
      }
      preViewLoading.value = false
    })
    .catch(() => {
      preViewLoading.value = false
    })
}
// 取消
const handleCacel = () => {
  router.back()
}
// 保存
const handleQuery = (isProview: boolean = false) => {
  return new Promise((resolve, reject) => {
    Promise.all([ruleFormRef.value.validate(), queryRef.value.validate()])
      .then(async valid => {
        if (valid[0] && valid[1]) {
          const params: any = {
            ...queryParams.value,
          }
          if (params.dateRange.length === 2) {
            params.recordStartTime = params.dateRange[0]
            params.recordEndTime = params.dateRange[1]
          } else {
            params.recordStartTime = undefined
            params.recordEndTime = undefined
          }
          delete params.dateRange
          if (isProview === true) {
            resolve(params)
            return
          }
          let saveApi: any
          if (params.id) {
            saveApi = updateInquiry
          } else {
            saveApi = saveInquiry
          }
          await saveApi(params)
          router.back()
        }
      })
      .catch(() => {
        ElMessage.warning('请完善表单信息')
        reject()
      })
  })
}

onMounted(() => {
  getNumberList()
  const { query } = route
  console.log('传参', query)
  if (query.type !== 'add' && query.id) {
    getDetail(query.id)
  }
})
</script>

<style scoped lang="scss">
.line-action {
  line-height: 37px;
  > i {
    margin: 5px;
    cursor: pointer;
    &:nth-child(1) {
      &:hover {
        color: var(--el-color-primary);
      }
    }
    &:nth-child(2) {
      &:hover {
        color: var(--el-color-danger);
      }
    }
  }
}
</style>
